<template>
  <el-tree
    style="max-width: 600px"
    default-expand-all
    :data="treeData"
    :props="defaultProps"
    @node-click="handleNodeClick"
    @node-contextmenu.prevent="handleNodeContextMenu"
  />

  <!-- 右键菜单 -->
  <div
    :style="{
      'z-index': 9999,
      position: 'fixed',
      left: optionCardX + 'px',
      top: optionCardY + 'px',
      width: '100px',
      background: 'white',
      'box-shadow': '0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)',
    }"
    v-show="optionCardShow"
    id="option-button-group"
  >
    <el-button @click="showAdd" class="option-card-button">添加</el-button>
    <el-button @click="showEdit" class="option-card-button">修改</el-button>
    <el-button @click="showdele" class="option-card-button">删除</el-button>
  </div>
  <!-- 添加组件 -->
  <Add ref="addChildRef" :pid="selectedNodePid" @refreshTable="initTableData" />
  <!-- 修改组件 -->
  <Edit
    ref="exitChildRef"
    :pid="selectedNodePid"
    :data="selectedNodeData"
    @refreshTable="initTableData"
  />
  <!-- 删除组件 -->
  <el-dialog
    v-model="centerDialogVisible"
    title="Warning"
    width="500"
    align-center
  >
    <span>确定要删除吗</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取消</el-button>
        &nbsp;
        <el-button type="primary" @click="deleteClick"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, watch, onUpdated } from "vue";
import Add from "./components/add.vue";
import Edit from "./components/edit.vue";
import { ElMessage } from "element-plus";
import http from "../../../util/http.js";
import { defineProps, defineEmits } from "vue";
// 定义
const addChildRef = ref(null);
const exitChildRef = ref(null);
const optionCardShow = ref(false);
const optionCardX = ref(100);
const optionCardY = ref(100);
const treeData = ref<TreeNode[]>([]);
const treeRef = ref();

// 树节点属性接口
interface TreeNode {
  id: string;
  text: string;
  icon: string;
  url: string;
  pid: string;
  order: number;
  flag: string;
  children?: TreeNode[];
}

// 自定义属性定义
const props = defineProps({
  checkedKeys: Array,
  showCheckbox: Boolean,
});

// 树节点属性映射
const defaultProps = {
  children: "children",
  label: "text",
};
// 左键点击处理事件
const handleNodeClick = (data: TreeNode) => {
  optionCardShow.value = false;
};
// 菜单加载
const initTableData = async () => {
  try {
    const response = await http.post("/menu/menutable");
    const result = response.data.rows;
    treeData.value = convertToTree(result);
    console.log(treeData.value);
  } catch (error) {
    ElMessage.error("菜单加载错误" + error);
  }
};
// 将数据转换为树状
const convertToTree = (data: TreeNode[]): TreeNode[] => {
  const result: TreeNode[] = [];
  const map: { [key: string]: TreeNode } = {};

  data.forEach((item) => {
    map[item.id] = { ...item, children: [] };
  });

  data.forEach((item) => {
    if (item.pid === "0") {
      result.push(map[item.id]);
    } else {
      if (map[item.pid]) {
        map[item.pid].children.push(map[item.id]);
      }
    }
  });

  return result;
};

// 右键点击事件处理
const selectedNodePid = ref<string | null>(null);
const selectedNodeData = ref<TreeNode | null>(null);

const handleNodeContextMenu = (e, data: TreeNode) => {
  e.preventDefault();

  selectedNodePid.value = data.id;
  selectedNodeData.value = data;

  optionCardX.value = e.clientX;
  optionCardY.value = e.clientY;
  optionCardShow.value = true;
};
// 关闭右键菜单
const closeMenu = () => {
  optionCardShow.value = false;
};
// 显示添加对话框
const showAdd = () => {
  optionCardShow.value = false;
  if (addChildRef.value) {
    addChildRef.value.dialogFormVisible = true;
  }
  optionCardShow.value = false;
};
// 显示修改对话框
const showEdit = () => {
  optionCardShow.value = false;
  if (exitChildRef.value) {
    exitChildRef.value.EditdialogForm = true;
  }
};

// 显示删除对话框
const centerDialogVisible = ref(false);
const showdele = () => {
  centerDialogVisible.value = true;
  optionCardShow.value = false;
};
// 节点删除
const deleteClick = async () => {
  centerDialogVisible.value = false;

  if (selectedNodeData.value) {
    try {
      const res = await http.post("/menu/deltable", {
        id: selectedNodeData.value.id,
      });
      if (res.code === 200) {
        ElMessage.success("删除成功");
        initTableData();
      } else {
        ElMessage.error("删除失败");
      }
    } catch (error) {
      ElMessage.error("删除失败");
    }
  } else {
    ElMessage.error("未选择节点");
  }
};
// 打开树节点的勾选

const checkedKeys = ref();
const showCheckbox = props.showCheckbox;
watch(
  () => props.showCheckbox,
  (newVal) => {},
  { immediate: true } //在组件挂载时立即执行一次
);
watch(
  () => props.checkedKeys,
  (newVal, old) => {
    console.log(123456788888);

    if (old === undefined) {
    } else {
      checkedKeys.value = newVal;

      const nodesList = [];
      checkedKeys.value.forEach((item) => {
        nodesList.push(item.id);
      });
      console.log(333, nodesList);

      const nodes = [];
      nodesList.forEach((item) => {
        const node = treeRef.value.getNode(item);

        nodes.push(item);
      });
      treeRef.value.setCheckedKeys(nodes, true);

      // treeRef.value.setCheckedKeys([1, 2, 3]);
    }
  }
);
// 勾选树节点
// const emit = defineEmits(["setLeafNodesChecked"]);
// emit("setLeafNodesChecked");

console.log(1212, checkedKeys);
const tree = ref(null);

// console.log(props.checkedKeys);
// checkedKeys.forEach((key) => {
//   console.log("999999" + key);
//   tree.value.setChecked(key, true);
// });

// 点击其他区域，关闭右键事件
const handleClickOutside = (event: MouseEvent) => {
  const optionCard = document.getElementById("option-button-group");
  if (optionCard && !optionCard.contains(event.target as Node)) {
    optionCardShow.value = false;
  }
};

onMounted(() => {
  initTableData();
  document.addEventListener("click", handleClickOutside);
  // tree.value.setCheckedKeys]);
});

onUnmounted(() => {
  document.removeEventListener("click", handleClickOutside);
});
</script>

<style scoped>
:deep(.el-dropdown) {
  position: fixed;
  z-index: 9999;
}

.el-tree .el-tree-node__expand-icon {
  font-size: 16px;
  color: #409eff;
}

.el-tree .el-tree-node__expand-icon.is-leaf {
  display: none;
}

.el-tree .el-tree-node__expand-icon {
  cursor: pointer;
}

:deep .option-card-button {
  width: 100%;
  border-radius: 0;
}
:deep .el-button + .el-button {
  margin: 0;
}
</style>
